package com.test.ssm.filter;

import com.test.ssm.util.Constants;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 徒有琴
 */
@WebFilter("*.html")
public class UserFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    String[] NEED_LOGIN = {"/teacher/.*", "/student/.*"};

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String path = request.getServletPath();
        for (String s : NEED_LOGIN) {//必须登录
            if (path.matches(s)) {
                HttpSession session = request.getSession();
                Object user = session.getAttribute(Constants.SESSION_USER);
                if (user == null) {
                    response.sendRedirect("/gologin.html");
                    return;
                }
                Integer type = (Integer) session.getAttribute(Constants.USER_TYPE);
                boolean check = false;
               // check = path.matches(type == Constants.USER_TYPE_TEACHER ? "/teacher/.*" : "/student/.*");
                switch (type) {
                    case Constants.USER_TYPE_STUDENT:
                        check = path.matches("/student/.*");
                        break;
                    case Constants.USER_TYPE_TEACHER:
                        check = path.matches("/teacher/.*");
                        break;
                }
                if (!check) {
                    response.sendRedirect("/gologin.html");
                    return;
                }
            }
        }
        filterChain.doFilter(request, response);
    }


    @Override
    public void destroy() {

    }
}
